package com.ruoyi.quality.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ruoyi.baseData.domain.Material;
import com.ruoyi.baseData.domain.MaterialType;
import com.ruoyi.baseData.domain.dto.MaterialExcelDto;
import com.ruoyi.common.core.exception.GlobalException;
import com.ruoyi.common.core.utils.bean.BeanUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.quality.domain.*;
import com.ruoyi.quality.domain.InspectionItem;
import com.ruoyi.quality.domain.dto.InspectionItemDto;
import com.ruoyi.quality.domain.vo.InspectionItemVo;
import com.ruoyi.quality.domain.vo.InspectionItemVo;
import com.ruoyi.quality.domain.vo.InspectionTaskVo;
import com.ruoyi.quality.mapper.InspectionItemMapper;
import com.ruoyi.quality.service.InspectionItemService;
import com.ruoyi.quality.mapper.InspectionItemMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 *
 */
@Service
public class InspectionItemServiceImpl implements InspectionItemService{

    @Resource
    InspectionItemMapper inspectionItemMapper;

    @Override
    public Page<InspectionItemVo> getInspectionItemByPage(InspectionItemDto pageEntity) {
        MPJLambdaWrapper<InspectionItem> wrapper = new MPJLambdaWrapper<InspectionItem>()
                .selectAll(InspectionItem.class)//查询user表全部字段
                .selectAs( Sampling::getName, InspectionItemVo::getSamplingName )
                //记的测试阶段
                .eq(InspectionItem::getDelFlag, 0)
                .leftJoin(Sampling.class, Sampling::getId, InspectionItem::getSamplingId)
                .orderByDesc(InspectionItem::getCreateTime);

        Page<InspectionItemVo> userList = inspectionItemMapper.selectJoinPage(new Page<>(pageEntity.getCurrentPage(), pageEntity.getPageSize()),   InspectionItemVo.class, wrapper);
        return userList;
    }

    @Override
    public void addInspectionItem(InspectionItemDto testDto) throws ParseException {
        String userName = SecurityUtils.getUsername();
        MPJLambdaWrapper<InspectionItem> wrapper = new MPJLambdaWrapper<InspectionItem>()
                .eq(InspectionItem::getCode, testDto.getCode())
                .ne(InspectionItem::getDelFlag, 1);
        InspectionItem material = inspectionItemMapper.selectOne(wrapper);
        if(null != material) {
            throw new GlobalException("该material已经存在");
        }
        InspectionItem test2 = new InspectionItem();
        BeanUtils.copyProperties(testDto, test2, new String[]{"id"});
        test2.setDelFlag(false);
        test2.setCreateBy(userName);
        test2.setCreateTime(new Date());
        inspectionItemMapper.insert(test2);
    }

    @Override
    public void updateInspectionItem(InspectionItemDto testDto) {
        String userName = SecurityUtils.getUsername();
        MPJLambdaWrapper<InspectionItem> wrapper = new MPJLambdaWrapper<InspectionItem>()
                .eq(InspectionItem::getId, testDto.getId())
                .ne(InspectionItem::getDelFlag, 1);
                ;
        InspectionItem inspectionItem = inspectionItemMapper.selectOne(wrapper);
        if(null == inspectionItem) {
            throw new GlobalException("该InspectionItem不存在");
        }
        BeanUtils.copyProperties(testDto, inspectionItem);
        inspectionItem.setUpdateBy(userName);
        inspectionItem.setUpdateTime(new Date());
        inspectionItemMapper.updateById(inspectionItem);
    }

    @Override
    public void delInspectionItem(InspectionItemDto testDto) {
        InspectionItem material = inspectionItemMapper.selectById(testDto.getId());
        if(null == material) {
            throw new GlobalException("该InspectionItem不存在");
        }
        material.setDelFlag(true);
        inspectionItemMapper.updateById(material);
    }

    @Override
    public String uploadInspectionItem(MultipartFile file) throws IOException {
        String msg = "";
        if(!file.getOriginalFilename().contains(".xlsx") && !file.getOriginalFilename().contains(".xls")) {
            return "文件格式不对";
        }
        EasyExcel.read(file.getInputStream(), InspectionItemDto.class, new ReadListener<InspectionItemDto>(){
            public static final int BATCH_COUNT = 1000;

            private List<InspectionItemDto> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

            @Override
            public void invoke(InspectionItemDto t, AnalysisContext analysisContext) {
                //UNIT如为空，默认取PCS
//                if(ObjectUtil.isNull(t.getTestTime())) {
//                    t.setTestTime(0);
//                }
//                if(ObjectUtil.isNull(t.getMaturingTime())) {
//                    t.setMaturingTime(0);
//                }
//                    t.setUnit("PCS");
////
//                //是否采集SN如为空，默认采集
//                if(ObjectUtil.isNull(t.getGetSn()))
//                    t.setGetSn(true);
//                //是否采集备注如为空，默认不采集
//                if(ObjectUtil.isNull(t.getGetComments()))
//                    t.setGetComments(false);
//                //Warehouse后台可默认写C01
//                if(ObjectUtil.isNull(t.getWarehouse())||  StringUtils.isEmpty(t.getWarehouse()))
//                    t.setWarehouse(DEFAULT_WAREHOUSE);
//                //Plant字段如为空，默认1001
//                if(ObjectUtil.isNull(t.getPlant())||  StringUtils.isEmpty(t.getPlant()))
//                    t.setPlant(DEFAULT_PLANT);
//                //长宽高不为空，自动计算体积，录入后台
//                if(!ObjectUtil.isNull(t.getLength())&& !ObjectUtil.isNull(t.getWidth()) && !ObjectUtil.isNull(t.getHeight()))
//                    t.setVolume(t.getLength()*t.getWidth()*t.getHeight().doubleValue());
//                //如ProductType/ProductFamily为空，根据t_product_type前缀与ProductType/ProductFamily绑定规则，匹配对应的ProductType/ProductFamily值
//                //todo:规则校验
//
//                for(ProductType productType:productTypeList)
//                {
//                    if(t.getMlfb().contains(productType.getMlfbPrefix()))
//                    {
//                        t.setProductType(productType.getProductType());
//                        t.setProductFamily(productType.getProductFamily());
//                        if(productType.getProductType().equals(LICENSE)) {
//                            t.setGetComments(true);
//                        }
//                        break;
//                    }
//                }

                cachedDataList.add(t);
                if (cachedDataList.size() >= BATCH_COUNT) {
                    // 这个是保存数据saveData();
                    // 存储完成清理 list
                    saveData();
                    cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
                }
            }
            @Override
            public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                saveData();
            }

            @Transactional
            private void saveData() {
                //todo: 如果pn重复
//                List<String> codes = cachedDataList.stream().map(item -> item.getCode()).distinct().collect(Collectors.toList());
//                MPJLambdaWrapper<Material> wrapper = new MPJLambdaWrapper<Material>()
//                        .selectAll(Material.class)
//                        .eq(Material::getDelFlag, 0)
//                        .in(Material::getCode,  codes)
//                        .orderByDesc(Material::getCreateTime);
//                /**
//                 * 存在的物料
//                 */
//                List<Material> exitMats = materialMapper.selectList(wrapper);
//                List<String> existCodes = exitMats.stream().map(item -> item.getCode()).distinct().collect(Collectors.toList());
//                List<MaterialExcelDto> materialExcelDtos = cachedDataList.stream().filter(item -> !existCodes.contains(item.getCode()))
//                        .collect(Collectors.toList());
//
//
//                MPJLambdaWrapper<MaterialType> wrapper2 = new MPJLambdaWrapper<MaterialType>()
//                        .selectAll(MaterialType.class)
//                        .eq(Material::getDelFlag, 0);
//                /**
//                 * 获取所有的物料类型
//                 */
//                List<MaterialType> materialTypes = materialTypeMapper.selectList(wrapper2);
                Integer i = 1;
                for(InspectionItemDto inspectionItemDto: cachedDataList) {
//                    Material material = new Material();
//                    String materialCode = materialExcelDto.getCode();
//                    Optional<MaterialType> optionalMaterialType = materialTypes.stream().filter(item -> materialCode.startsWith(item.getCode())).findFirst();
//                    if(optionalMaterialType.isPresent()) {
//                        MaterialType materialType = optionalMaterialType.get();
//                        material.setMaterialTypeId(materialType.getId());
//                    }
                    InspectionItem inspectionItem = new InspectionItem();

                    BeanUtils.copyProperties(inspectionItemDto, inspectionItem, new String[]{"id"});
                    inspectionItem.setCode("质检项" + i);
                    inspectionItem.setCreateTime(new Date());
                    inspectionItem.setCreateBy("System");
                    inspectionItem.setDelFlag(false);
                    inspectionItemMapper.insert(inspectionItem);
                    i = i + 1;
                }
//                List<Material> exitMats = materialRepository.findMaterialsByPnInAndDelete(pns, 0);
//                List<String> existPns = exitMats.stream().map(item -> item.getPn()).distinct().collect(Collectors.toList());
//                List<Material> materials = cachedDataList.stream().filter(item -> !existPns.contains(item.getPn()))
//                        .map(materialMapper::toEntity).collect(Collectors.toList());
//                materialRepository.saveAll(materials);
            }
        }).sheet(0).headRowNumber(1).doRead();
        return msg;
    }
}




